﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace ManageData
{
    public class MySaveChangesInterceptor : SaveChangesInterceptor
    {
        public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
        {
            Console.WriteLine($"正在保存修改： {eventData.Context.Database.GetConnectionString()}");
            return result;
        }

        public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = new CancellationToken())
        {
            Console.WriteLine($"正在异步保存修改： {eventData.Context.Database.GetConnectionString()}");
            Console.WriteLine($"正在取消异步保存修改： {eventData.Context.Database.GetConnectionString()}");
            var suppressResult = InterceptionResult<int>.SuppressWithResult(-1);
            return new ValueTask<InterceptionResult<int>>(suppressResult);
        }

        public override int SavedChanges(SaveChangesCompletedEventData eventData, int result)
        {
            Console.WriteLine($"已保存修改： {eventData.Context.Database.GetConnectionString()}");
            return base.SavedChanges(eventData, result);
        }

        public override ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default)
        {
            Console.WriteLine($"已异步保存修改： {eventData.Context.Database.GetConnectionString()}");
            return base.SavedChangesAsync(eventData, result, cancellationToken);
        }

        public override void SaveChangesFailed(DbContextErrorEventData eventData)
        {
            Console.WriteLine($"保存修改失败： {eventData.Context.Database.GetConnectionString()}");
            base.SaveChangesFailed(eventData);
        }

        public override Task SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken = default)
        {
            Console.WriteLine($"异步保存修改失败： {eventData.Context.Database.GetConnectionString()}");
            return base.SaveChangesFailedAsync(eventData, cancellationToken);
        }

    }
}
